package controllers

import (
	// "fmt"
	"log"
	"time"

	"face/facesdk"
	"face/models"
	"github.com/astaxie/beego"
)

// 获取face列表
type FaceListController struct {
	beego.Controller
}

// 获取所有的face列表
func (c *FaceListController) Get() {
	facelist := make([]*models.Face, 0, 10)

	err := models.Engine.Find(&facelist)
	if err != nil {
		log.Println(err)
		c.Data["json"] = GetErrorMessage("Get List Failed")
		c.ServeJson()
		return
	}

	c.Data["json"] = map[string]interface{}{"Faces": facelist}
	c.ServeJson()
}

// 手动添加一个face
type FaceAddController struct {
	beego.Controller
}

func (c *FaceAddController) Get() {
	faceUrl := c.GetString("FaceUrl")
	if faceUrl == "" {
		c.Data["json"] = GetErrorMessage("Required Param FaceUrl")
		c.ServeJson()
		return
	}

	face := new(models.Face)

	// 自动上传到face++ 上检测
	faceaddId, imgid, err := facesdk.CreateFace(faceUrl)
	if err != nil {
		log.Println(err)
		c.Data["json"] = GetErrorMessage("Create Face Failed")
		c.ServeJson()
		return
	}

	face.ImgId = imgid
	face.FaceUrl = faceUrl
	face.FaceAddId = faceaddId
	face.CreateTime = time.Now().Unix()

	n, err := models.Engine.Insert(face)
	if err != nil {
		log.Println(err)
		c.Data["json"] = GetErrorMessage("Create Face Failed")
		c.ServeJson()
		return
	}
	c.Data["json"] = GetSuccessData(n)
	c.ServeJson()
	return

}

// 删除face
type FaceDeleteController struct {
	beego.Controller
}

func (c *FaceDeleteController) Get() {
	key := c.GetString("key")
	c.Data["json"] = map[string]string{"key": key}
	c.ServeJson()
}

// 修改face参数
type FaceUpdateController struct {
	beego.Controller
}

func (c *FaceUpdateController) Get() {
	key := c.GetString("key")
	c.Data["json"] = map[string]string{"key": key}
	c.ServeJson()
}

// 获取face详情
// 是face++ 上的详情
type FaceDetailController struct {
	beego.Controller
}

func (c *FaceDetailController) Get() {
	// faceId
	faceId, err := c.GetInt64("FaceId")
	if faceId == 0 || err != nil {
		c.Data["json"] = GetErrorMessage("Requited Param FaceId")
		c.ServeJson()
		return
	}

	face := new(models.Face)

	face.FaceId = faceId

	has, err := models.Engine.Get(face)
	if err != nil {
		c.Data["json"] = GetErrorMessage("InvaideParams")
		c.ServeJson()
		return
	}

	if !has {
		c.Data["json"] = GetErrorMessage("InvaideParams")
		c.ServeJson()
		return
	}

	if face.ImgId == "" {
		c.Data["json"] = GetErrorMessage("InvaideParams")
		c.ServeJson()
		return
	}

	c.Data["json"] = map[string]interface{}{"info": facesdk.GetFaceInfo(face.ImgId)}
	c.ServeJson()
	return
}
